package flink.dataset;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.util.FileUtils;
import org.junit.Test;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author binarylei
 * @version 2019-11-29
 */
public class DistributeCacheDataSetTest {

    /**
     * 将远程的文件缓存到本地
     */
    @Test
    public void testDistributedCache() throws Exception {
        final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        // filepath可以是远程的目录文件，eg: hdfs://master:8020/cache.txt
        env.registerCachedFile("/home/cache.txt", "cache.txt");

        // <id, name>
        DataSource<Tuple2<Long, String>> names = env.fromElements(
                new Tuple2<Long, String>(1L, "john"),
                new Tuple2<Long, String>(2L, "mick"),
                new Tuple2<Long, String>(3L, "bai"));
        names.map(new RichMapFunction<Tuple2<Long, String>, Tuple2<Long, String>>() {
            Map<Long, Integer> broadcastMap = new HashMap<>();

            /**
             * 方法只会执行一次，可以执行初始化功能
             */
            @Override
            public void open(Configuration parameters) throws Exception {
                super.open(parameters);

                // 获取缓存文件
                File file = getRuntimeContext()
                        .getDistributedCache().getFile("cache.txt");
                String content = FileUtils.readFile(file, "utf-8");
                System.out.println(content);
            }

            @Override
            public Tuple2<Long, String> map(Tuple2<Long, String> t)
                    throws Exception {
                return t;
            }
        }).print();

    }
}
